#include "core\TextBox.h"
#include <Windows.h>

TextBox::TextBox()
{
  m_width = 0;
  m_height = 0;
  clear();
}

void TextBox::addMessage(const char* fmt, ...)
{
  char text[512];
  va_list ap;
  if(fmt == 0) return;
  va_start(ap, fmt);
  vsprintf(text, fmt, ap);
  va_end(ap);
  std::string msg(text);
  m_msgList.push_back(msg);
  createBox();
}

void TextBox::setWidth(int w)
{
  m_width = w;
}

void TextBox::setHeight(int h)
{
  m_height = h;
}

int TextBox::getWidth()
{
  return m_width;
}

int TextBox::getHeight()
{
  return m_height;
}

void TextBox::clear()
{
  m_msgList.clear();
  for(int i=0;i<64;i++)for(int j=0;j<256;j++) m_textBox[i][j] = '\0';
  createBox();
}

char* TextBox::getLine(int i)
{
  if(i >= m_height) return NULL;
  return m_textBox[i];
}

void TextBox::createBox()
{
  if(m_width <= 0 || m_height <= 0) return;
  int index = m_height - 1;
  for(int m=m_msgList.size()-1;m>=0;m--)
  {
    std::string s = m_msgList[m];
    std::vector<std::string> lines;
    int p = 0;
    lines.push_back(s.substr(p, m_width));
    p += m_width;
    while(p < (int)s.length())
    {
      lines.push_back(" " + s.substr(p, m_width - 1));
      p += m_width - 1;
    }
    for(int l=lines.size()-1;l>=0;l--)
    {
      sprintf_s(m_textBox[index], 256, "%s", lines[l].c_str());
      index--;
      if(index < 0) return;
    }
  }
}
